//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.restaurant.application.accumulategoodscoupon;

import com.google.common.collect.Lists;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.alarm.alarmclock.AlarmClock;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.DateTypes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.TableShell;
import com.nebutown.commonunits.dataface.definitions.DynamicResult;
import com.nebutown.commonunits.dataface.definitions.DynamicValue;
import com.nebutown.commonunits.dataface.definitions.FieldValue;
import com.nebutown.commonunits.dataface.definitions.PageForm;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.description.data.SortSpec;
import com.nebutown.generation.basicdata.StringMap;
import com.nebutown.generation.basictype.StringData;
import com.nebutown.generation.basictype.UID;
import com.nebutown.supporthome.AbstractImpl;
import com.restaurant.application.accumulategoods.support.GoodsData;
import com.restaurant.application.accumulategoodscoupon.support.AbstractAccumulateGoodsCoupon;
import com.restaurant.application.accumulategoodscoupon.support.GoodsCouponData;
import com.restaurant.application.couponmanage.CouponManage;
import com.restaurant.application.couponmanagecl.CouponManageCL;
import com.restaurant.application.couponmanagecs.CouponManageCS;
import com.restaurant.application.indexes.accumulategoodslist.AccumulateShop;
import com.restaurant.application.indexes.accumulategoodslist.mysql.AccumulateGoodsListBean;
import com.restaurant.application.indexes.accumulategoodslist.mysql.AccumulateGoodsListCriteria;
import com.restaurant.application.indexes.accumulategoodslist.mysql.AccumulateGoodsListImpl;
import com.restaurant.application.indexes.couponmanagelist.AssistCouponManageList;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListBean;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListCriteria;
import com.restaurant.application.indexes.couponmanagelist.mysql.CouponManageListImpl;
import com.restaurant.application.level.Level;
import com.restaurant.application.levelset.LevelSet;
import com.restaurant.application.minifacade.data.CardBO;
import com.restaurant.application.shop.Shop;
import com.restaurant.application.util.CommonUtils;
import com.restaurant.application.util.ResultBean;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class AccumulateGoodsCouponImpl extends AbstractAccumulateGoodsCoupon {
    public AccumulateGoodsCouponImpl() {
    }

    public ViewUpdate save(GoodsCouponData save, int[] seq) {
        FormShell formShell = this.newFormShell(save.duplicate(), DataModes.VALIDATE, true);
        boolean b = formShell.dataFailedValidation();
        if (b) {
            PageForm pageForm = this.newFormShell(save, DataModes.VALIDATE, true).getForm();
            return this.returnView(new View[]{((UIDataFace)this.getSingleton(UIDataFace.class)).newUniForm(this.unitPosition(), pageForm)});
        } else {
            save.withModifyTime(DateTimeUtils.getCurrentMillisecond());
            if (Objects.nonNull(save.getAccessLevel()) && save.getAccessLevel().size() > 0) {
                save.getAccessLevel().forEach((x) -> {
                    List<UID> collect = (List)((LevelSet)this.getSingleton(LevelSet.class)).findAllLevel().stream().filter((e) -> {
                        return Objects.equals(((Level)this.getUnit(Level.class, e)).findData().getMemberName(), x);
                    }).collect(Collectors.toList());
                    if (collect.size() > 0) {
                        save.getLevelUid().add((UID)collect.get(0));
                    }

                });
            }

            save.withCreateTime(this.getData().getCreateTime());
            save.withGoodsId(this.getData().getGoodsId());
            if (Objects.nonNull(save.getImmediately()) && save.getImmediately()) {
                this.getData().setForSellTime(DateTimeUtils.getCurrentMillisecond());
                this.getData().setState("已上架");
            }

            save.setGoodsCategory("优惠券");
            if (Objects.nonNull(this.getData().getCouponManagementId()) && !Objects.equals(save.getCouponManagementId().getDisplay(), this.getData().getCouponManagementId().getDisplay()) && Objects.nonNull(this.getData().getSoldNumber()) && this.getData().getSoldNumber() > 0L || Objects.nonNull(this.getData().getSoldNumber()) && this.getData().getSoldNumber() > save.getTotalNUmber()) {
                return this.returnViewCall(this.buildViewCall(this.unitPosition(), "showErrorMessage", (List)null, (new StringMap()).putData("errorMessage", "修改失败，商品已卖出时不能修改优惠券的种类，商品总数量不能小于已卖出的数量")));
            } else {
                if (Objects.nonNull(save.getCouponManagementId())) {
                    List<CouponManageListBean> search = ((CouponManageListImpl)this.getIndex(CouponManageListImpl.class)).search((new CouponManageListCriteria()).withNumberEquals(save.getCouponManagementId().getDisplay()), (SortSpec)null, 1);
                    if (search.size() <= 0) {
                        return this.returnViewCall(this.buildViewCall(this.unitPosition(), "showErrorMessage", (List)null, (new StringMap()).putData("errorMessage", "没有该优惠券请先创建")));
                    }

                    if (Objects.nonNull(save.getRemoveTime()) && ((CouponManageListBean)search.get(0)).getEndTime() < save.getRemoveTime()) {
                        return this.returnViewCall(this.buildViewCall(this.unitPosition(), "showErrorMessage", (List)null, (new StringMap()).putData("errorMessage", "优惠券的最大使用时间应大于商品的下架时间")));
                    }

                    String[] split = ((CouponManageListBean)search.get(0)).getShopNameList().split(",");
                    if (split.length > 0) {
                        String collect = null;
                        List uids;
                        if (((CouponManageListBean)search.get(0)).getCouponManageUid().value().contains("CouponManageCL")) {
                            uids = (List)((CouponManageCL)this.getUnit(CouponManageCL.class, ((CouponManageListBean)search.get(0)).getCouponManageUid())).findData().getShopList().stream().map((e) -> {
                                return e.getShopUid();
                            }).collect(Collectors.toList());
                            collect = (String)uids.stream().map((e) -> {
                                return ((Shop)this.getUnit(Shop.class, (UID) e)).findData().getId();
                            }).collect(Collectors.joining(","));
                        } else if (((CouponManageListBean)search.get(0)).getCouponManageUid().value().contains("CouponManageCS")) {
                            uids = (List)((CouponManageCS)this.getUnit(CouponManageCS.class, ((CouponManageListBean)search.get(0)).getCouponManageUid())).findData().getShopList().stream().map((e) -> {
                                return e.getShopUid();
                            }).collect(Collectors.toList());
                            collect = (String)uids.stream().map((e) -> {
                                return ((Shop)this.getUnit(Shop.class, (UID) e)).findData().getId();
                            }).collect(Collectors.joining(","));
                        } else if (((CouponManageListBean)search.get(0)).getCouponManageUid().value().contains("CouponManage")) {
                            uids = (List)((CouponManage)this.getUnit(CouponManage.class, ((CouponManageListBean)search.get(0)).getCouponManageUid())).findData().getShopList().stream().map((e) -> {
                                return e.getShopUid();
                            }).collect(Collectors.toList());
                            collect = (String)uids.stream().map((e) -> {
                                return ((Shop)this.getUnit(Shop.class, (UID) e)).findData().getId();
                            }).collect(Collectors.joining(","));
                        }

                        save.withUseShopId(collect);
                    }

                    if (Objects.isNull(save.getRemoveTime())) {
                        save.setRemoveTime(((CouponManageListBean)search.get(0)).getEndTime());
                    }

                    Long amount = 0L;
                    List<AccumulateGoodsListBean> search1 = ((AccumulateGoodsListImpl)this.getIndex(AccumulateGoodsListImpl.class)).search((new AccumulateGoodsListCriteria()).withGoodsUIDNotEquals(this.getId()).withCouponManagementEquals(((CouponManageListBean)search.get(0)).getCouponManageUid().toString()), (SortSpec)null, 100);
                    if (search1.size() > 0) {
                        amount = search1.stream().mapToLong(AccumulateGoodsListBean::getGoodsNumber).sum();
                    }

                    if (amount + save.getTotalNUmber() > Long.valueOf(((CouponManageListBean)search.get(0)).getTotalAmount())) {
                        return this.returnViewCall(this.buildViewCall(this.unitPosition(), "showErrorMessage", (List)null, (new StringMap()).putData("errorMessage", "优惠券不够了")));
                    }

                    save.withCouponManagement(((CouponManageListBean)search.get(0)).getCouponManageUid());
                    save.withCouponName(((CouponManageListBean)search.get(0)).getModality());
                    save.withState("已上架");
                    save.withUseShopName(((CouponManageListBean)search.get(0)).getShopNameList());
                }

                save.withSoldNumber(this.getData().getSoldNumber());
                this.setData(save);
                if (Objects.nonNull(this.getData().getRemoveTime())) {
                    setAlarmClock(this, "remove", this.getData().getRemoveTime());
                }

                if (Objects.nonNull(this.getData().getForSellTime())) {
                    setAlarmClock(this, "forSell", this.getData().getForSellTime());
                }

                if (Objects.isNull(this.getData().getCreateTime())) {
                    this.getData().setGoodsId(CommonUtils.getGoodsNumber(this));
                    this.getData().setCreateTime(DateTimeUtils.getCurrentMillisecond());
                    this.insertToTable();
                }

                this.quickIndexUpdate();
                return this.returnPushInContainer(((AccumulateShop)this.getSingleton(AccumulateShop.class)).getId(), false);
            }
        }
    }

    public ViewUpdate selectCoupon(GoodsCouponData selectCoupon, int[] seq) {
        System.out.println("我来了");
        PageForm pageForm = this.newFormShell(selectCoupon, DataModes.EDIT, true).getForm();
        return this.returnView(new View[]{((UIDataFace)this.getSingleton(UIDataFace.class)).newUniForm(this.unitPosition(), pageForm)});
    }

    private void insertToTable() {
        GoodsCouponData duplicate = this.getData().duplicate();
        AccumulateGoodsListBean bean = new AccumulateGoodsListBean();
        bean.withAccumulatePoints(duplicate.getAccumulatePoints()).withCreateTime(duplicate.getCreateTime()).withModifyTime(duplicate.getModifyTime()).withGoodsNumber(duplicate.getTotalNUmber()).withGoodsDescribe(duplicate.getGoodsDescribe()).withGoodsId(duplicate.getGoodsId()).withGoodsName(duplicate.getGoodsName()).withGoodsUID(this.getId()).withSoldNumber(0L).withGoodsType("优惠券").withState(duplicate.getState()).withShopId(duplicate.getUseShopId()).withCouponManagement(this.getData().getCouponManagement().value()).withExchangeLevel(Objects.nonNull(this.getData().getAccessLevel()) ? this.getData().getAccessLevel().toString() : "");
        ((AccumulateGoodsListImpl)this.getIndex(AccumulateGoodsListImpl.class)).insert(bean);
    }

    public ViewUpdate cancel(int[] seq) {
        return this.returnPushInContainer(((AccumulateShop)this.getSingleton(AccumulateShop.class)).getId(), false);
    }

    public ViewUpdate searchCoupon(StringData searchCoupon, int[] seq) {
        List<CardBO> allNormal = ((AssistCouponManageList)this.getSingleton(AssistCouponManageList.class)).getAllNormal();
        List<CardBO> collect = (List)allNormal.stream().filter((e) -> {
            return Objects.isNull(searchCoupon) || Objects.isNull(searchCoupon.get()) || e.getCardId().contains(CommonUtils.removeNullStr(searchCoupon.get()));
        }).collect(Collectors.toList());
        DynamicResult result = new DynamicResult();

        for(int i = 0; i < collect.size(); ++i) {
            result.addValues((new DynamicValue()).withDisplay(((CardBO)collect.get(i)).getCardId()).withRecordId((long)i));
        }

        return this.returnViewCall(this.buildViewCall(this.unitPosition(), "dynamicSearch", (List)null, result));
    }

    public GoodsData getGoodsData() {
        return (new GoodsData()).withAccumulatePoints(this.getData().getAccumulatePoints()).withGoodsId(this.getData().getGoodsId()).withGoodsName(this.getData().getGoodsName()).withAccessLevel(this.getData().getAccessLevel()).withImages(this.getData().getImages());
    }

    public ResultBean<UID> exchangeCouponGoods() {
        ResultBean resultBean = new ResultBean();
        String result = "success";
        if (Objects.isNull(this.getData().getSoldNumber())) {
            this.getData().setSoldNumber(0L);
        }

        if (this.getData().getTotalNUmber() - this.getData().getSoldNumber() > 0L) {
            UID couponManagement = this.getData().getCouponManagement();
            List<CouponManageListBean> search = ((CouponManageListImpl)this.getIndex(CouponManageListImpl.class)).search((new CouponManageListCriteria()).withCouponManageUidEquals(couponManagement), (SortSpec)null, 1);
            if (search.size() > 0) {
                UID couponUid = null;
                CouponManageListBean bean = (CouponManageListBean)search.get(0);
                if ("代金券".equals(bean.getType())) {
                    couponUid = ((CouponManage)this.getUnit(CouponManage.class, couponManagement)).createCoupon();
                } else if ("满减券".equals(bean.getType())) {
                    couponUid = ((CouponManageCL)this.getUnit(CouponManageCL.class, couponManagement)).createCoupon();
                } else if ("折扣券".equals(bean.getType())) {
                    couponUid = ((CouponManageCS)this.getUnit(CouponManageCS.class, couponManagement)).createCoupon();
                }

                if (Objects.isNull(couponUid)) {
                    result = "该优惠券无法领取";
                }

                resultBean.setData(couponUid);
            }

            if (Objects.equals(result, "success")) {
                this.getData().setSoldNumber(this.getData().getSoldNumber() + 1L);
            }

            resultBean.setMessage(result);
            return resultBean;
        } else {
            resultBean.setMessage("数量不足");
            return resultBean;
        }
    }

    public UID getCouponManagement() {
        return this.getData().getCouponManagement().duplicate();
    }

    public void upDateState(String state) {
        if (Objects.equals(state, "已上架")) {
            this.getData().setForSellTime(DateTimeUtils.getCurrentMillisecond());
            if (Objects.nonNull(this.getData().getRemoveTime()) && this.getData().getRemoveTime() < DateTimeUtils.getCurrentMillisecond()) {
                this.getData().setRemoveTime((Long)null);
            }

            this.getData().setState(state);
        }

        if (Objects.equals(state, "已下架") || Objects.equals(state, "已上架") || Objects.equals(state, "已删除")) {
            this.getData().setState(state);
        }

        this.quickIndexUpdate();
    }

    public View showGoodsCouponDetail(String uniPosition) {
        PageForm pageForm = this.newFormShell(this.getData().duplicate(), DataModes.SHOW, false).getForm();
        return ((UIDataFace)this.getSingleton(UIDataFace.class)).newUniForm(uniPosition, pageForm);
    }

    public View getFullView() {
        PageForm pageForm = this.newFormShell(this.getData().duplicate(), DataModes.EDIT, true).getForm();
        return ((UIDataFace)this.getSingleton(UIDataFace.class)).newUniForm(this.unitPosition(), pageForm);
    }

    public View getViewLead(ViewSpec viewSpec) {
        return null;
    }

    private FormShell newFormShell(GoodsCouponData criteria, DataModes modes, Boolean edit) {
        FormShell formShell = new FormShell("积分商城/优惠券商品创建", 3, 10);
        formShell.source(criteria, modes);
        formShell.at(0, 0, "优惠券号").dynamicEntry("couponManagementId", criteria.getCouponManagementId(), this.getPath(CMD_SEARCHCOUPON, new int[0]), this.getPath(CMD_SELECTCOUPON, new int[0])).notNull();
        List<CouponManageListBean> search = Lists.newArrayList();
        if (Objects.nonNull(criteria.getCouponManagementId()) && Objects.nonNull(criteria.getCouponManagementId().getDisplay())) {
            search = ((CouponManageListImpl)this.getIndex(CouponManageListImpl.class)).search((new CouponManageListCriteria()).withNumberEquals(criteria.getCouponManagementId().getDisplay()), (SortSpec)null, 1);
            if (((List)search).size() > 0 && Objects.nonNull(criteria.getGoodsName())) {
                criteria.withGoodsName(((CouponManageListBean)((List)search).get(0)).getModality());
            }
        }

        formShell.at(0, 1, "商品描述").stringField("goodsDescribe", criteria.getGoodsDescribe()).placeHolder("商品描述").notNull().setEditable(edit);
        formShell.at(1, 0, "商品名称").stringField("goodsName", criteria.getGoodsName()).placeHolder("商品名称").notNull().setEditable(edit);
        formShell.at(3, 0, "图片").styles("", "height:200px").imageentryField("images", criteria.getImages()).notNull().setEditable(edit);
        TableShell<CouponManageListBean> tableShell = new TableShell(CouponManageListBean.class, (List)search);
        tableShell.createColumn("number").withName("优惠券号").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(bean.getNumber());
        });
        tableShell.createColumn("type").withName("类型").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(bean.getType());
        });
        tableShell.createColumn("modality").withName("券名").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(bean.getModality());
        });
        tableShell.createColumn("createTime").withName("有效期").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(DateTimeUtils.toTime(bean.getReceiveTime()) + "-" + DateTimeUtils.toTime(bean.getEndTime()));
        });
        tableShell.createColumn("shopNameList").withName("适用门店").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(bean.getShopNameList());
        });
        tableShell.createColumn("limitId").withName("领用限制").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(this.getStr(bean));
        });
        tableShell.createColumn("totalAmount").withName("发行量").cellCalculator((b) -> {
            CouponManageListBean bean = (CouponManageListBean)b;
            return (new FieldValue()).withValue(String.valueOf(bean.getTotalAmount()));
        });
        formShell.at(2, 0, "商品表").large(3, 1).tableField("inset", tableShell);
        List<UID> allLevel = ((LevelSet)this.getSingleton(LevelSet.class)).findAllLevel();
        List<String> levelList = (List)allLevel.stream().map((e) -> {
            return ((Level)this.getUnit(Level.class, e)).findData().getMemberName();
        }).collect(Collectors.toList());
        formShell.at(4, 0, "兑换级别").multipleChoice("accessLevel", levelList).placeHolder("兑换级别").notNull().setEditable(edit);
        formShell.at(5, 0, "所需积分").longField("accumulatePoints", criteria.getAccumulatePoints()).placeHolder("所需积分").notNull().setEditable(edit);
        formShell.at(5, 1, "总数量").longField("totalNUmber", criteria.getTotalNUmber()).placeHolder("总数量").notNull().setEditable(edit);
        formShell.at(6, 0, "立即上架").checkentryField("immediately", criteria.getImmediately()).placeHolder("立即上架").setEditable(edit);
        formShell.at(7, 0, "上架时间").dateEntryField("forSellTime", criteria.getForSellTime(), DateTypes.DATETIME).placeHolder("上架时间").setEditable(edit);
        formShell.at(7, 1, "下架时间").dateEntryField("removeTime", criteria.getRemoveTime(), DateTypes.DATETIME).placeHolder("下架时间").setEditable(edit);
        if (edit) {
            formShell.at(9, 0, "").buttonField(this.getPath(CMD_SAVE, new int[0]), "保存", "", true);
        }

        formShell.at(9, 1, "").buttonField(this.getPath(CMD_CANCEL, new int[0]), "取消", "", true);
        return formShell;
    }

    private String getStr(CouponManageListBean bean) {
        String buffer = "";
        if (Objects.nonNull(bean)) {
            if (Objects.nonNull(bean.getLimitAccount())) {
                buffer = buffer + "每个用户内仅限" + bean.getLimitAccount() + "张";
            }

            if (Objects.nonNull(bean.getLimitId())) {
                buffer = buffer + "每个用户仅限领" + bean.getLimitId() + "张";
            }
        }

        return buffer;
    }

    public AccumulateGoodsListBean getGoodsUIDDataForAccumulateGoodsList(AccumulateGoodsListBean bean) {
        GoodsCouponData data = this.getData().duplicate();
        bean.withAccumulatePoints(data.getAccumulatePoints()).withCreateTime(data.getCreateTime()).withModifyTime(data.getModifyTime()).withGoodsNumber(data.getTotalNUmber()).withGoodsDescribe(data.getGoodsDescribe()).withGoodsId(data.getGoodsId()).withGoodsName(data.getGoodsName()).withGoodsUID(this.getId()).withSoldNumber(this.getData().getSoldNumber()).withGoodsType(data.getGoodsCategory()).withShopId(this.getData().getUseShopId()).withTypeId(data.getTypeId()).withShopName(this.getData().getUseShopName()).withState(this.getData().getState()).withUpTime(this.getData().getForSellTime()).withDownTime(this.getData().getForSellTime()).withExchangeLevel(Objects.nonNull(this.getData().getAccessLevel()) ? this.getData().getAccessLevel().toString() : "").withCouponManagement(Objects.nonNull(this.getData().getCouponManagement()) ? this.getData().getCouponManagement().value() : "");
        return bean;
    }

    public static void setAlarmClock(AbstractImpl impl, String mark, Long time) {
        ((AlarmClock)impl.getSingleton(AlarmClock.class)).setDelayAlarmClock(impl.getId().toString() + mark, time - DateTimeUtils.getCurrentMillisecond() / 1000L, impl.getId());
    }
}
